package diona.search.yasearch

import org.joda.time.DateTime
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.joda.time.format.DateTimeFormat
import xml.{XML, Utility, Elem}
import net.liftweb.common.Logger
import collection.immutable.List
import diona.search.PostInfo

/**
 * User: anton
 * Date: 03.07.11 13:50
 */
object YaSearch extends Logger
{

  private val formatter = DateTimeFormat.forPattern("yyyyMMdd'T'HHmmss")
  private val requestDateFormatter = DateTimeFormat.forPattern("yyyyMMdd")

  private val yandexUrl = "http://xmlsearch.yandex.ru/xmlsearch?user=n-g-safonova&key=03" +
    ".36012581:f084ea7377b89a0b7a5b6f3a2ddf9067"

  @volatile var search: (String, DateTime, DateTime) => List[PostInfo] =
    (query, from, to) => {
      var result = List[PostInfo]()
      query match {
        case "" => debug("Nothing to send for yandex search")
        case _ =>
          val request: Elem =
            <request>
              <query>{String.format("%s date:%s..%s", query, requestDateFormatter.print(from),
                requestDateFormatter.print(to))}</query>
              <groupings>
		            <groupby attr="" mode="flat" groups-on-page="1000"  docs-in-group="1000" />
	            </groupings>
            </request>
          val client = new DefaultHttpClient()
          val update = new HttpPost(yandexUrl)
          update.setEntity(new StringEntity(Utility.toXML(request).toString(), "application/xml", "utf-8"))
          val response = XML.load(client.execute(update).getEntity.getContent)
          for (grouping <- (response \\ "grouping")) {
            for (group <- (grouping \\ "group")) {
              for (document <- (group \\ "doc")) {
                result = new PostInfo(
                  url = (document \ "url").text,
                  tstamp = formatter.parseDateTime((document \ "modtime").text),
                  isComment = false) :: result
              }
            }
          }
      }
      result
    }

}